package com.cf.base.comm.widget.watermark;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import com.cf.base.comm.R;
import com.cf.base.comm.tools.BaseSingleton;
import com.cf.base.comm.tools.DisplayUtils;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yangji
 */
public class WatermarkUtils {

    private WatermarkUtils() {
    }

    public static BaseSingleton<WatermarkUtils> singleton = new BaseSingleton<WatermarkUtils>() {
        @Override
        protected WatermarkUtils create() {
            return new WatermarkUtils();
        }
    };

    private String watermarkText = "";
    private int textColor = 0x90C1C1C1;
    private int textSize = 20;
    private Application application;
    private boolean isRegister = false;
    private Map<Integer, WeakReference<WatermarkView>> weakReferenceMap = new ConcurrentHashMap<>();

    @SuppressLint("UseSparseArrays")
    public void init(Application application) {
        if (!isRegister) {
            this.application = application;
            isRegister = true;
            initWatermark();
            register();
        }
    }

    private void initWatermark() {
        textSize = DisplayUtils.singleton.get().sp2px(textSize);
    }

    public WatermarkUtils setTextColor(int textColor) {
        this.textColor = textColor;
        return this;
    }

    public WatermarkUtils setTextSize(int textSize) {
        this.textSize = DisplayUtils.singleton.get().sp2px(textSize);
        return this;
    }

    public WatermarkUtils setWatermarkText(String watermarkText) {
        this.watermarkText = watermarkText;
        return this;
    }

    public void update() {
        for (WeakReference<WatermarkView> referenceView : weakReferenceMap.values()) {
            WatermarkView view = referenceView.get();
            if (view != null) {
                view.setTextColor(textColor);
                view.setTextSize(textSize);
                view.setWatermarkText(watermarkText);
            }
        }
    }

    private String getWatermarkText() {
        return watermarkText;
    }

    private void register() {
        application.registerActivityLifecycleCallbacks(new BaseActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                if (activity instanceof FragmentActivity) {
                    ((FragmentActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(new FragmentManager.FragmentLifecycleCallbacks() {
                        @Override
                        public void onFragmentResumed(@NonNull FragmentManager fm, @NonNull Fragment f) {
                            super.onFragmentResumed(fm, f);
                            //拦截dialog
                            if (f instanceof DialogFragment) {

                                Dialog d = ((DialogFragment) f).getDialog();
                                if (d != null && d.getWindow() != null) {
                                    addWatermarkView(f, d.getContext(), d.getWindow());
                                }
                            }
                        }

                        @Override
                        public void onFragmentDetached(@NonNull FragmentManager fm, @NonNull Fragment f) {
                            super.onFragmentDetached(fm, f);
                            weakReferenceMap.remove(f.hashCode());
                        }
                    }, true);
                }
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                //拦截Activity
                addWatermarkView(activity, activity.getWindow());
            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                super.onActivityDestroyed(activity);
                weakReferenceMap.remove(activity.hashCode());
            }
        });
    }

    /**
     * 添加 DialogFragment/Activity 水印
     *
     * @param context fragment.dialog.context/activity
     * @param window  fragment.dialog.window/activity.window
     */
    private void addWatermarkView(Fragment fragment, Context context, Window window) {
        if (window.findViewById(R.id.comm_lib_watermark_view_id) == null) {
            WatermarkView view = new WatermarkView(context);
            view.setWatermarkText(getWatermarkText());
            window.addContentView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            view.setTextColor(textColor);
            view.setTextSize(textSize);
            weakReferenceMap.put(fragment.hashCode(), new WeakReference<>(view));
        }

    }


    /**
     * 添加 DialogFragment/Activity 水印
     *
     * @param activity fragment.dialog.context/activity
     * @param window   fragment.dialog.window/activity.window
     */
    private void addWatermarkView(Activity activity, Window window) {
        if (window.findViewById(R.id.comm_lib_watermark_view_id) == null) {
            WatermarkView view = new WatermarkView(activity);
            view.setWatermarkText(getWatermarkText());
            window.addContentView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
            view.setTextColor(textColor);
            view.setTextSize(textSize);
            weakReferenceMap.put(activity.hashCode(), new WeakReference<>(view));
        }
    }
}
